<template>
  <div>
    <el-main>
      <div style="margin-bottom: 30px">
      </div>

      <div style="margin: 10px 0">
        <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
        <el-input v-model="msg" @input="changeMessage(msg)" style="width: 200px;margin-left: 1300px;margin-right: 5px" placeholder="请输入用户名" suffix-icon="el-icon-search"></el-input>
        <el-button type="primary" @click="handleSearch(msg,userPageSize)">搜索</el-button>
      </div>
      <el-table :data="tableData" border stripe :header-cell-class-name="headerBg">
        <el-table-column prop="id" label="id" width="80" align="center"></el-table-column>
        <el-table-column prop="cardname" :show-overflow-tooltip="true" align="center" label="用户名" width="300"></el-table-column>
        <el-table-column label="昵称" width="300" align="center" prop="username"></el-table-column>
        <el-table-column label="权限" width="300" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.type === 0">管理员</p>
            <p v-else="scope.row.type === 1">普通用户</p>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" width="400" :formatter="dateTimeFormatter"
                         label="创建时间" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="success" plain @click="dialogEditUserOpen(scope.row)"
                       style="margin-left: 10px; margin-right: 10px">编辑</el-button>
            <el-popconfirm
              confirm-button-text='确认'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除这一条问答吗？"
              @confirm="deleteUser(scope.row.cardname)">
              <el-button type="danger" plain slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="userCurrent"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="userPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userTotal">
        </el-pagination>
      </div>
      <el-dialog title="编辑用户" :visible.sync="editUserVisible" align="center" @close="resetUserValue" :close-on-click-modal="false" width="30%">
        <el-form :v-model="userUpdateFrom" @submit.native.prevent :label-width="formLabelWidth">
          <el-form-item label="账号: "  style="margin-right: 45px" >
            <el-input v-model="userUpdateFrom.username" autocomplete="off" value=""></el-input>
          </el-form-item>
          <el-form-item label="姓名: "  style="margin-right: 45px">
            <el-input v-model="userUpdateFrom.cardname" autocomplete="off" value=""></el-input>
          </el-form-item>
          <el-form-item label="密码: "  style="margin-right: 45px">
            <el-input v-model="userUpdateFrom.password" autocomplete="off" value=""></el-input>
          </el-form-item>
          <el-form-item style="margin-right: 65px">
            <el-button type="primary" @click="userUpdateOnSubmit">保存</el-button>
            <el-button @click="editUserVisible = false">取消</el-button>
            <el-button @click="resetUserValue">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog title="新增用户" :visible.sync="addUserVisible" align="center" :close-on-click-modal="false" width="30%">
        <el-form :label-width="formLabelWidth" align="center" :rules="rules" ref="ruleForm">
          <el-form-item label="账号: "  style="margin-right: 45px">
            <el-input v-model="addForm.username" placeholder="请输入登录名" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户名: "  style="margin-right: 45px">
            <el-input v-model="addForm.cardname" placeholder="请输入用户名" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码: "  style="margin-right: 45px">
            <el-input v-model="addForm.password" placeholder="请输入密码" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item style="margin-right: 45px">
            <el-button type="primary" @click="userOnSubmit">保存</el-button>
            <el-button @click="addUserVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-main>
  </div>
</template>

<script>
  import axios from "axios";
  import moment from "moment";

  export default {
    name: "Administrator",
    data() {
      return{
        baseURL: 'http://localhost:8082',
        tableData: [],
        userTotal: 0,
        userPageSize: 10,
        userCurrent: 1,
        userValue: {},
        user: {},
        msg: '',

        editUserVisible: false,
        addUserVisible: false,

        addForm: {},
        userFrom: {},
        userUpdateFrom: {},
        headerBg: "headerBg",
        formLabelWidth: "90px",

        rules: {
          username: [
            {required: true, message: '账号不能为空', trigger: 'blur'},
            {min: 1, max: 10, message: '长度在 1 到 20 个字符', trigger: 'blur'}
          ],
          cardname: [
            {required: true, message: '用户名不能为空', trigger: 'blur'},
            {min: 1, max: 10, message: '长度在 1 到 20 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
          ],
        }

      }
    },
    created() {
      //请求分页查询数据
      this.load();
    },
    methods: {
      //页面初始化加载
      load(){
        this.handleSearch()
      },

      //搜索功能 同时用于数据更改后的页面刷新
      handleSearch() {
        axios({
          method:'post',
          params:{
            cardname: this.msg,
            pageNum: this.userCurrent,
            pageSize: this.userPageSize,
          },
          url: this.baseURL+'/user/find-user-by-cardname?'
        }).then((res)=>{
          this.tableData = res.data.data.records
          this.userTotal = res.data.data.total
          this.userCurrent = res.data.data.current
          this.userPageSize = res.data.data.size
        })
      },

      dialogEditUserOpen(row) {
        this.editUserVisible = true
        this.userUpdateFrom = row
        this.userValue.cardname = this.userUpdateFrom.cardname
        this.userValue.username = this.userUpdateFrom.username
        this.userValue.password = this.userUpdateFrom.password
      },

      handleAdd(){
        this.addUserVisible = true
        this.addForm = {}
      },

      deleteUser(cardname){
        axios({
          method:'post',
          params:{
            cardname: cardname
          },
          url: this.baseURL+'/user/delete-user-by-cardname?'
        }).then((res)=>{
          if(res.data.status == "SUCCESS" && res.status == 200){
            this.$message.success("删除用户成功！")
            this.handleSearch()
          } else {
            this.$message.error("删除用户失败！")
          }
        })
      },

      userOnSubmit(){
        // this.$refs['addForm'].validate((valid) => {
        //   if (valid) {
            axios({
              method:'post',
              params:{
                username: this.addForm.username,
                cardname: this.addForm.cardname,
                password: this.addForm.password,
                createUserId: localStorage.getItem("id"),
              },
              url: this.baseURL+'/user/add-user?'
            }).then((res)=>{
              if(res){
                if(res.data.status == "SUCCESS"){
                  this.$message.success("新增用户成功！")
                  this.addUserVisible = false
                  this.handleSearch()
                } else {
                  this.$message.error("新增用户失败！" + res.data.msg)
                }
              }
            }).catch(error =>{
              this.$message.error("新增用户失败！原因： "+ error)
            })
        //   }
        // });
      },

      userUpdateOnSubmit(){
        // this.$refs['addForm'].validate((valid) => {
        //   if (valid) {
        axios({
          method:'post',
          params:{
            id: this.userUpdateFrom.id,
            username: this.userUpdateFrom.username,
            cardname: this.userUpdateFrom.cardname,
            password: this.userUpdateFrom.password,
          },
          url: this.baseURL+'/user/update-user?'
        }).then((res)=>{
          if(res){
            if(res.data.status == "SUCCESS"){
              this.$message.success("更新用户信息成功！")
              this.editUserVisible = false
              this.handleSearch()
            } else {
              this.$message.error("更新用户信息失败！" + res.data.msg)
            }
          }
        }).catch(error =>{
          this.$message.error("更新用户信息失败！原因： "+ error)
        })
        //   }
        // });
      },

      //重置回答内容
      //回答对话框关闭时 恢复未保存的值
      resetUserValue(){
        this.userUpdateFrom.username = this.userValue.username
        this.userUpdateFrom.cardname = this.userValue.cardname
        this.userUpdateFrom.password = this.userValue.password
      },

      //搜索input框值实时显示
      changeMessage(msg) {
        this.msg = msg;
        //强制刷新渲染
        this.$forceUpdate();
      },

      //分页控制
      handleSizeChange(pageSize) {
        this.userPageSize = pageSize;
        this.handleSearch();
      },
      handleCurrentChange(pageNum) {
        this.userCurrent = pageNum;
        this.handleSearch();
      },
      //日期格式
      dateTimeFormatter(row, column) {
        var dateTime = row[column.property];
        if (dateTime === undefined) {
          return "";
        }
        return moment(dateTime).format("YYYY-MM-DD HH:mm:ss");
      },
    }
  }
</script>

<style>

  .headerBg {
    background: #eee !important;
  }

  .el-tooltip__popper{
    max-width:20%;
  }
</style>


